{% extends "base.html" %} {% block main %}
<div id="root"></div>
<script type="text/babel">
    class Room extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                users: [],
                messages: []
            };
        }
        addToUserList = user => {
            this.setState({
                users: [...this.state.users, user]
            });
        }
        addMessage = msg => {
            this.setState({
                messages: [...this.state.messages, msg]
            });
        }
        removeFromUserList = user => {
            this.setState({
                users: this.state.users.filter(item => item.id != user.id)
            });
        }
        componentDidMount(){
            var ws = new WebSocket('ws://127.0.0.1:3000/ws/chat');
            ws.onmessage = (event) => {
                var data = event.data;
                console.log(data);
                var msg = JSON.parse(data);
                if (msg.type === 'list') {
                    console.log("list",msg.data)
                    this.setState({
                        users: msg.data
                    });
                } else if (msg.type === 'join') {
                    this.addToUserList(msg.user);
                    this.addMessage(msg);
                } else if (msg.type === 'left') {
                    this.removeFromUserList(msg.user);
                    this.addMessage(msg);
                } else if (msg.type === 'chat') {
                    this.addMessage(msg);
                }
            }
            ws.onclose = function (evt) {
                console.log('[closed] ' + evt.code);
                var input = $('#form-chat').find('input[type=text]');
                input.attr('placeholder', 'WebSocket disconnected.');
                input.attr('disabled', 'disabled');
                $('#form-chat').find('button').attr('disabled', 'disabled');
            };
            ws.onerror = function (code, msg) {
                console.log('[ERROR] ' + code + ': ' + msg);
            };

            var chatForm = document.getElementById('form-chat');
            chatForm.addEventListener('submit', function (e) {
                e.preventDefault();
                var inputDom = document.getElementById("chat");
                var text = inputDom.value.trim();
                console.log('[chat] ' + text);
                if (text) {
                    inputDom.value = '';
                    ws.send(text);
                }
            })
        }
        render() {
            const {users, messages} = this.state;
            return (
                <div>
                    <div id="message-list">
                        {messages.map(msg=>(
                            <div key={msg.id}>
                                { (msg.type=="join" || msg.type=="left") && <h4>{msg.data}</h4> }
                                {
                                    msg.type=="chat" &&
                                    <React.Fragment>
                                        <h4>{msg.user.name}:</h4>
                                        <span>{msg.data}</span>
                                    </React.Fragment>
                                }
                            </div>
                        ))}
                    </div>
                    <form id="form-chat">
                        <input id="chat" type="text" />
                        <button type="submit">发送</button>
                    </form>
                    <hr />
                    <div id="user-list">
                        {users.map(item => (
                            <h4 key={item.id}>{item.name} ({item.id})</h4>
                        ))}
                    </div>
                </div>
            )
        }
    }

    ReactDOM.render(
    <Room />,
            document.getElementById('root')
    );
</script>
{% endblock %}